function displayResult(item, val, text) {
    vm.product.id = val;
}

var orderItem = new Array();

var productSelec = function () {
    $.ajax({
        url: "/sys/product/prodoctList",
        data: {'nameOrCode': $("#searchString").val()},
        dataType: 'json',
        success: function (data) {
            $('#searchString').typeahead({
                source:data.data,
                itemSelected: displayResult
            });
        }
    });
}


var priceTotal = function (productId) {
    var orderTotal = 0;
    var price = document.getElementById("price"+productId).value;
    var num = document.getElementById("num"+productId).value;

    var totalPrice = price*num;
    var total = document.getElementById("totalPrice"+productId);
    total.value = totalPrice;

    $.each(orderItem,function(index,value) {
        if(value.id == productId){
            if(num > value.number){
                var msg = value.supplierName+"--"+value.name+"--"+value.model+"--"+value.material+"--"+"库存不足，现有库存"+value.number+"  请及时补充！！！";
                var errorMsg = document.getElementById("errorMsg");
                errorMsg.innerText = msg;
            }

            value.numBuyer = num;
            value.price = price;
            value.totalPrice = totalPrice;
        }
        orderTotal = Number(orderTotal)+Number(value.totalPrice);
    })

    vm.orders.totalPrice = orderTotal;
}

var delOrderItem = function (productId) {
    var orderTotalPrice = 0;
    $.each(orderItem,function(index,value) {
        if(value.id == productId){
            orderItem.splice(index,1);
            var orderItems = document.getElementById("orderItem");
            var m = document.getElementById("orderItem"+productId);
            orderItems.removeChild(m);
        }
        orderTotalPrice = Number(orderTotalPrice)+Number(value.totalPrice);
    })
    vm.orders.totalPrice = orderTotalPrice;
}

$(function () {

    $('#datetimeStart').datetimepicker({
        format: 'yyyy-mm-dd',  //显示格式可为yyyymm/yyyy-mm-dd/yyyy.mm.dd
        autoclose: true,
        minView : 'month',
        initialDate: new Date(),	//初始化日期.默认new Date()当前日期
        forceParse: false,  	//当输入非格式化日期时，强制格式化。默认true
        language: 'zh-CN' //语言
    })


    $('#datetimeEnd').datetimepicker({
        format: 'yyyy-mm-dd',  //显示格式可为yyyymm/yyyy-mm-dd/yyyy.mm.dd
        autoclose: true,
        minView : 'month',
        initialDate: new Date(),	//初始化日期.默认new Date()当前日期
        forceParse: false,  	//当输入非格式化日期时，强制格式化。默认true
        language: 'zh-CN' //语言
    })


    productSelec();

    $("#searchString").on("change",function () {
        productSelec();
    })


    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/orders/list',
        datatype: "json",
        colModel: [			
			{ label: '业务员', name: 'userName', index: 'user_id', width: 60 },
			{ label: '订单号', name: 'orderNum', index: 'order_num', width: 90 },
            { label: '采购商', name: 'shopName', index: 'user_id', width: 80 },
            // { label: '订单类型', name: 'type', index: 'type', width: 80 ,
            //     formatter: function (cellvalue, options, rowObject) {
            //         if (cellvalue == 0) {
            //             return "出货单"
            //         } else if (cellvalue == 1) {
            //             return "进货单"
            //         }
            // }},
			{ label: '运费', name: 'logisticsFee', index: 'logistics_fee', width: 60 },
			{ label: '总价', name: 'totalPrice', index: 'total_price', width: 60 },
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 100,
                formatter:'date',formatoptions: {srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'}
            },
            { label: '备注', name: 'remark', index: 'remark', width: 100 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        searchString:null,
		showList: true,
		orderAdd: false,
		title: null,
		orders: {
            type:0,
            orderItems:[]
        },
        product:{
		    shopId:null
        },
        searchString:"",
        searcher:{
		    userName:null,
            orderNo:null,
            shopName:null,
            datetimeStart:null,
            datetimeEnd:null
        },
        supplierList:[],
        userList:[]
    },

	methods: {
		query: function () {
		    vm.searcher.datetimeStart = $("#datetimeStart").val();
		    vm.searcher.datetimeEnd = $("#datetimeEnd").val();
			vm.reload();
		},
        download: function () {
            vm.searcher.datetimeStart = $("#datetimeStart").val();
            vm.searcher.datetimeEnd = $("#datetimeEnd").val();

            window.location.href = "/sys/orders/download?userName="+vm.searcher.userName+"&orderNo="+vm.searcher.orderNo+"&shopName="+vm.searcher.shopName+"&datetimeStart="+vm.searcher.datetimeStart+"&datetimeEnd="+vm.searcher.datetimeEnd;
        },
		add: function(){
			vm.showList = false;
            vm.orderAdd = true;
			vm.title = "录入出货单";
            vm.supplier();
            vm.user();
			vm.orders = {type:0,totalPrice:0,logisticsFee:0,shopId:null};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.orderAdd = true;
            vm.title = "修改/查看";
            
            vm.getInfo(id)
		},
        preview: function(event){
            var orderTotal = 0;
            $.each(orderItem,function(index,value) {
                orderTotal = Number(orderTotal)+Number(value.totalPrice);
            })
            vm.orders.totalPrice = orderTotal;

            var url = vm.orders.id == null ? "sys/orders/save" : "sys/orders/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.orders),
                success: function(r){
                    console.log(r);
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            window.open("/sys/orders/preview?orderId="+r.order.id);
                            setTimeout(vm.reload(),2000);
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		saveOrUpdate: function (event) {
		    var orderTotal = 0;
            $.each(orderItem,function(index,value) {
                orderTotal = Number(orderTotal)+Number(value.totalPrice);
            })
            vm.orders.totalPrice = orderTotal;

			var url = vm.orders.id == null ? "sys/orders/save" : "sys/orders/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.orders),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
                            window.location.reload();
                        });
					}else{
						alert(r.msg);
					}
				}
			});
		},
        orderTmpAdd: function (event) {
            $.ajax({
                url: "/sys/product/"+vm.product.id,
                dataType: 'json',
                success: function (data) {
                    vm.searchString = "";
                    var product =  data.product;
                   product["totalPrice"] = 0;
                   product["numBuyer"] = 0;
                   var bl = false;
                    $.each(orderItem,function(index,value) {
                        if(value.id == product["id"]){
                            bl = true;
                        }
                    })
                    if(bl){
                        alert("产品已添加！！！");
                    }else {
                        orderItem.push(product);
                        vm.orders.orderItems = orderItem;
                        var orderItemDetail = "";
                        orderItemDetail += "<div class=\"form-group\" id='orderItem"+product.id+"'>";
                        orderItemDetail += "<div class=\"col-sm-2 control-label\">商品信息:  </div>";
                        orderItemDetail += "<div class=\"col-sm-4\" style='padding-top:7px;margin-bottom:0;text-align:left'>"+product.supplierName+"--"+product.name+"--"+product.model+"--"+product.material+" </div>";
                        orderItemDetail += "<div class=\"col-sm-1\">";
                        orderItemDetail += "<input type=\"text\" class=\"form-control\" placeholder=\"售价\" id='price"+product.id+"'  value = "+product.price+" onchange='priceTotal("+product.id+")'/>";
                        orderItemDetail += "</div>";
                        orderItemDetail += "<div class=\"col-sm-1\">";
                        orderItemDetail += "<input type=\"text\" class=\"form-control\" placeholder=\"数量\" id='num"+product.id+"' onchange='priceTotal("+product.id+")'/>";
                        orderItemDetail += "</div>";
                        orderItemDetail += "<div class=\"col-sm-1\">";
                        orderItemDetail += "<input type=\"text\" class=\"form-control\" readonly id='totalPrice"+product.id+"' placeholder=\"总价\"/>";
                        orderItemDetail += "</div>";
                        orderItemDetail += "<div class=\"col-sm-1\">";
                        orderItemDetail += " <a class='btn btn-primary' onclick='delOrderItem("+product.id+")'><i class=\"fa fa-trash-o\"></i>&nbsp;删除</a>";
                        orderItemDetail += "</div>";
                        orderItemDetail += "</div>";
                        $("#orderItem").append(orderItemDetail);
                    }
                }
            });
        },
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/orders/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
		    window.location.href = baseURL + "sys/orders/info/"+id;
		},
		reload: function (event) {
			vm.showList = true;
            vm.orderAdd = false;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'userName': vm.searcher.userName,
                    "orderNo": vm.searcher.orderNo,
                    "shopName": vm.searcher.shopName,
                    "datetimeStart": vm.searcher.datetimeStart,
                    "datetimeEnd": vm.searcher.datetimeEnd
                },
                page:page
            }).trigger("reloadGrid");
		},
        supplier: function () {
            $.get(baseURL + "sys/supplier/purchasers?type=2", function(r){
                vm.supplierList = r.data;
            });
        },
        user: function () {
            $.get(baseURL + "sys/user/lists", function(r){
                console.log(r.data)
                vm.userList = r.data;
            });
        }
	}
});